package solution;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

class Solution {
    /**
     *69. x 的平方根
     * https://leetcode.cn/problems/sqrtx/description/
     */
    public int mySqrt(int x) {
        double i = 1.0;
        while(i < x) {
        if(i * i >= x) {
            break;
        }
        i += 0.1;
        }
        return (int)i;
    }
    /**
     *581. 最短无序连续子数组
     * https://leetcode.cn/problems/shortest-unsorted-continuous-subarray/description/
     */
    public int findUnsortedSubarray(int[] nums) {
        int len = nums.length;
        if(len == 1) {
            return 0;
        }
        int[] numsB = Arrays.copyOf(nums, len);
        Arrays.sort(numsB);
        //左边界
        int left = 0;
        //右边界
        int right = len - 1;
        //找出左边界第一个不同的下标
        for(int i = 0; i < len; i++) {
            if(numsB[i] == nums[i]) {
                left++;
            } else {
                break;
            }
        }
        //遍历完了，left == len，即这个数组是有序的，则返回0
        if(left == len) return 0;
        //找右边界第一个不相等的下标
        for(int i = len - 1; i >= 0; i--) {
            if(numsB[i] == nums[i]) {
                right--;
            } else {
                break;
            }
        }
        return right - left + 1;
    }
    /**
     *242. 有效的字母异位词
     * https://leetcode.cn/problems/valid-anagram/description/
     */
    public boolean isAnagram(String s, String t) {
        if (s.length() != t.length()) {
            return false;
        }
        int[] numS = new int[26];
        int[] numT = new int[26];
        for(int i = 0; i < s.length(); i++) {
            numS[s.charAt(i) - 'a']++;
        }
        for(int i = 0; i < t.length(); i++) {
            numT[t.charAt(i) - 'a']++;
        }
        for(int i = 0; i < 26; i++) {
            if(numS[i] == numT[i]) {
                continue;
            } else {
                return false;
            }
        }
        return true;
    }
    /**
     * 202. 快乐数
     * https://leetcode.cn/problems/happy-number/description/
     * @param n
     * @return
     */
    public static boolean isHappy(int n) {
        Set<Integer> set = new HashSet<>();
        int result = 0;
        int flg;
        do {
            while(n > 0) {
                int tmp = n % 10;
                result += tmp * tmp;
                n /= 10;
            }
            if(!set.contains(result)) {
                set.add(result);
            } else {
                return false;
            }
            n = result;
            flg = result;
            result = 0;
        } while (flg != 1);
        return true;
    }
}